<template>
    <div style="width: 100%;height: 100%;">
        <el-row>
            <div style="margin: 10px;">相机选择</div>
            <el-select v-model="device" style="width: 10%;margin: 10px;" placeholder="请选择">
                <el-option v-for="item in devices" :label="item.label" :value="item.deviceId">
                </el-option>
            </el-select>
            <el-button type="primary" @click="checkCarema" style="margin: 10px;left: 0;" plain>视频检测</el-button>
            <!-- <video ref="video" style="width: 50%;height: 20vh;" autoplay muted></video> -->
        </el-row>
        <el-row>
            <video ref="video" style="height: 20vh;margin: 10px;" autoplay muted></video>
        </el-row>
        <el-row>
            <div style="margin: 10px;">音频选择</div>
            <el-select v-model="audio" placeholder="请选择" style="width: 10%;margin: 10px;">
                <el-option v-for="item in audios" :label="item.label" :value="item.deviceId">
                </el-option>
            </el-select>
            <el-button type="primary" @click="checkAudio" style="margin: 10px;" plain>声音检测</el-button>
            <div id="progressBar" style="width: 0; height: 20px; background-color: #4caf50;margin-top: 10px;"></div>
        </el-row>
        <el-row>
            <div style="margin: 10px;">用户名称</div>
            <el-input v-model="name" style="width: 240px;margin-left: 10px;" placeholder="Please input" />
            <el-button type="primary" @click="setName" style="margin: 10px;" plain>名称设置</el-button>
        </el-row>
    </div>
</template>
<script>
import { onMounted, ref } from 'vue';
import { videoStore } from '@/store/video'
import * as signalR from '@microsoft/signalr';
import { SignalrStore } from '@/store/signalrStore'
import { userStore } from '@/store/userStore'
export default {
    setup() {
        var devices = ref([]);
        var device = ref();
        var audios = ref([]);
        var audio = ref();
        var video = ref();
        var connection = null;
        var name = ref();
        window.addEventListener('unload', function (event) {
            // 在页面即将被卸载时执行的操作
            // 你可以在这里执行你想要的事件，比如发送请求、保存数据等

            // 这里可以添加你的自定义逻辑
            window.gc();
            console.log(111);
        });
        onMounted(async () => {
            var a=navigator;
            debugger
            var devicesData = await navigator.mediaDevices.enumerateDevices();
            if (devicesData && devicesData.length > 0) {
                devices.value = devicesData.filter(s => s.kind === 'videoinput');
                audios.value = devicesData.filter(s => s.kind === 'audioinput');
            }
        })
        const checkAudio = async () => {
            try {
                var stream = await navigator.mediaDevices.getUserMedia({ audio: { deviceId: { exact: audio.value } } });
                // 创建音频上下文
                var audioContext = new AudioContext();
                var analyser = audioContext.createAnalyser();

                // 获取音频流源
                var source = audioContext.createMediaStreamSource(stream);
                source.connect(analyser);

                // 设置音频分析器
                analyser.fftSize = 256;
                var bufferLength = analyser.frequencyBinCount;
                var dataArray = new Uint8Array(bufferLength);

                // 获取声音大小并更新进度条
                function updateProgress() {
                    analyser.getByteFrequencyData(dataArray);
                    var total = 0;
                    for (var i = 0; i < bufferLength; i++) {
                        total += dataArray[i];
                    }
                    var average = total / bufferLength;
                    var progressBar = document.getElementById('progressBar');
                    progressBar.style.width = average + 'px';

                    requestAnimationFrame(updateProgress);
                }
                videoStore().setAudio(audio.value);
                // 开始更新进度条
                updateProgress();
            } catch (error) {
                alert('相机设备和音频设备不存在')
                return;
            }
        }
        const checkCarema = async () => {
            var stream = await navigator.mediaDevices.getUserMedia({ video: { deviceId: { exact: device.value } } });
            video.value.srcObject = null;
            video.value.srcObject = stream;
            video.value.play();
            videoStore().setVideo(device.value);
        }
        const setName = async () => {
            if(videoStore().getName()!='')
            {
                alert('已经设置了名字'+videoStore().getName());
                return;
            }
            videoStore().setName(name.value);
            var res = await fetch('/configjs.json?d=' + new Date());
            var urlData = await res.json();
            var urls = urlData.signalrUrl + '?name=' + videoStore().getName();
            connection = new signalR.HubConnectionBuilder()
                .withUrl(urls) // 指定您的 Hub 的 URL
                .build();
            // connection.qs = { Name: }
            await connection.start();
            videoStore().setConnectionId(connection.connectionId);
            SignalrStore().setSignalrInstance(connection);
            alert("名称设置成功。");
        }
        return { devices, device, audios, audio, checkAudio, video, checkCarema, name, setName }
    }
}
</script>